package pw.hais.etgsh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.okhttp.Response;

import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import pw.hais.etgsh.R;
import pw.hais.etgsh.adapter.ArticleAdapter;
import pw.hais.etgsh.app.BaseActivity;
import pw.hais.etgsh.dao.ArticleDao;
import pw.hais.etgsh.model.ArticleModel;
import pw.hais.etgsh.model.GuShiTypeModel;
import pw.hais.http.base.OnHttpListener;
import pw.hais.utils.EmptyUtil;
import pw.hais.utils.L;
import pw.hais.utils.SPUtils;

/**
 * 海涵，内涵图片、段子
 * Created by Hais1992 on 2015/12/16.
 */
public class ArticleListActivity extends BaseActivity implements AdapterView.OnItemClickListener, PtrHandler, AbsListView.OnScrollListener {
    public static final String INTENT_GUSHIMODEL_KEY = "INTENT_GUSHIMODEL_KEY";
    public String SP_ARTICLE_LIST_PAGE_KEY = "SP_ARTICLE_LIST_PAGE";
    private ListView listview;
    private PtrClassicFrameLayout store_house_ptr_frame;
    private ArticleAdapter articleAdapter;
    private GuShiTypeModel guShiTypeModel;
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);


        guShiTypeModel = (GuShiTypeModel) getIntent().getSerializableExtra(INTENT_GUSHIMODEL_KEY);
        if(guShiTypeModel==null){
            finish();
        }

        getSupportActionBar().setTitle(guShiTypeModel.title);
        SP_ARTICLE_LIST_PAGE_KEY = SP_ARTICLE_LIST_PAGE_KEY+guShiTypeModel.title;
        int sp_page = SPUtils.getObject(SP_ARTICLE_LIST_PAGE_KEY, Integer.class, 0);
        if (sp_page > 0) {
            L.showShort("已为你跳转到 第 " + sp_page + "页");
            page = sp_page;
        }


        listview = (ListView) findViewById(R.id.listview_haihan);
        listview.setOnItemClickListener(this);
        store_house_ptr_frame = (PtrClassicFrameLayout) findViewById(R.id.store_house_ptr_frame);
        store_house_ptr_frame.setPtrHandler(this);

        View headerView = LayoutInflater.from(context).inflate(R.layout.activity_list_header, null);
        ((TextView) headerView.findViewById(R.id.text_title)).setText(guShiTypeModel.title+"\n\n\t\t"+guShiTypeModel.content);
        View footerView = LayoutInflater.from(context).inflate(R.layout.activity_list_footer, null);
        listview.addHeaderView(headerView);
        listview.addFooterView(footerView);
        listview.setOnScrollListener(this);

        loadDialogShow("数据初始化中...");
        getHttpDataAndShow(page + "");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        SPUtils.saveObject("now_position", position);
        Intent intent = new Intent(context, ArticleDetailsActivity.class);
        intent.putExtra(ArticleDetailsActivity.INTENT_CONTENT_Id_KEY, articleAdapter.getItem(position-1).id);
        startActivityForResult(intent, 222);
    }


    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, listview, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        page = 1;
        getHttpDataAndShow(page + "");
        listview.setSelection(0);
        SPUtils.delObject(SP_ARTICLE_LIST_PAGE_KEY);
    }


    private void getHttpDataAndShow(final String page) {
        ArticleDao.getList(guShiTypeModel.url, page, new OnHttpListener<List<ArticleModel>>() {
            @Override
            public void onSuccess(Response response, List<ArticleModel> data) {
                loadDialogDismiss();
                if (EmptyUtil.emptyOfList(data)) {
                    L.showShort("没有内容！");
                    return;
                }
                if (articleAdapter == null) {
                    articleAdapter = new ArticleAdapter(data, ArticleAdapter.ViewHolder.class);
                    listview.setAdapter(articleAdapter);
                } else if ("1".equals(page)) {
                    articleAdapter.removeListData();
                }

                articleAdapter.appendData(data);
                store_house_ptr_frame.refreshComplete();
            }

        });
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
            // 当不滚动时
            case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                // 判断滚动到底部
                if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                    page = page + 1;
                    SPUtils.saveObject(SP_ARTICLE_LIST_PAGE_KEY, page);
                    getHttpDataAndShow(page + "");
                }
                break;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_article, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            startActivity(new Intent(context, AuthorActivity.class));
            return true;
        }  else if (id == R.id.action_delete) {
            SPUtils.delObject(SP_ARTICLE_LIST_PAGE_KEY);
            page = 1;
            store_house_ptr_frame.autoRefresh();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 333) {
            int position = SPUtils.getObject("now_position", Integer.class);
            if (articleAdapter.getCount() > position) {
                position = position + 1;
                onItemClick(null, null, position, 0);
                listview.setSelection(position);
            } else {
                L.showShort("请翻页后继续 ");
            }
        }
    }
}
